iT邦幫忙

2022 iThome 鐵人賽

DAY 6
0
自我挑戰組

30天Java由淺入深系列 第 6

Day 6 : Variables( 2 )

  • 分享至 

  • xImage
  •  

Primitive v.s Non-Primitive

Different variables are stored in memory in different ways. In Java, we can simply divide the data types of variables into two types:

  • Primitive Data Types
  • Non-Primitive Data Types

Primitive

As the name suggests, they are immutable (immutable) variables that have been defined (predfined) in Java. They are processed using the code-by-value method, which means that their values (stack memory addresses) are directly copied when passed in memory.
-> Includes: numbers (integers and decimals), characters char, Boolean boolean

Non-Primitive

Also known as Reference Types / Object type, because the way it stores values in memory is by reference (heap memory address). It is not defined in advance in Java and needs to be created by the programmer.
-> Includes: String*, Array*, Classes*, etc.

Difference

  1. Primitives are already defined, and non-primitives need to be designed.
  2. Non-primitives can be used to call functions to execute operating procedures, while primitives cannot.
  3. Primitive data type variables always have a value, while non-primitives can be null (NULL).
  4. The size of a primitive variable depends on its type, while non-primitives are all the same size.

String Methods

Now we know that a String is a class in Java that is made up of a sequence of characters. Then provide some practical keywords to make the use of strings more flexible!!!

  • length() → Calculate the length of a string
String code = "Hello World!";
System.out.println( code.length() );     //Output : 12

Program analysis: When calculating the length of a string, spaces and punctuation are included. And remember to add a period (.) before a keyword when you want to use a command.

  • toUpperCase() & toLowerCase() → Convert all words to upper or lower case
  • concat (StringName) → combine two strings
String greeting = "Hello ";
String person = "Chi";
String NewG = greeting.toUpperCase();
String NewP = person.toLowerCase();
System.out.println(NewG.concat(NewP));       //Outputs : HELLO chi
  • indexOf(” ”) → returns the index of the first occurrence of the searched string (if there are multiple occurrences, the first occurrence is returned)
    → by the way: for strings and arrays, the first index is always 0
String txt = "Please locate where 'locate' occurs!";
System.out.println( txt.indexOf("locate") );     // Outputs 7  (內容注意使用雙引號)

/images/emoticon/emoticon12.gif


上一篇
Day 5 : Variables( 1 )
下一篇
Day 7 : Operators and Mathematical Calculations
系列文
30天Java由淺入深30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
鰻魚燒
iT邦新手 4 級 ‧ 2022-12-10 20:34:21

String NewG = greeting.toUppercase();

這裡的toUppercase()應該改成 toUpperCase(),大小寫寫錯跑起來會有error發生

謝謝您的指教,已經更正!

我要留言

立即登入留言